﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WeChatApp.Helper;
using Microsoft.Extensions.Configuration;
using SqlSugar;

namespace WeChatApp.Repositories
{
    public class RepositoryFactory
    {
        public SqlSugarClient DBModel{ get; set; }

        public RepositoryFactory(IConfiguration config)
        {
            SqlSugarClient sqlSugarClient = DBHelper.InitialSqlSugarClient(config["ConnectString"]);
            DBModel = sqlSugarClient;
        }
        public RepositoryFactory(string connectString)
        {
            SqlSugarClient sqlSugarClient = DBHelper.InitialSqlSugarClient(connectString);
            DBModel = sqlSugarClient;
        }
        public TBiz GetRepository<TBiz>()
            where TBiz : BaseRepository, new ()
        {
            TBiz biz = new TBiz();
            biz.SetEntitiesModel(DBModel);
            return biz;
        }
        public ISugarQueryable<dynamic> QueryDynamicForDict(string sqlStr, Dictionary<string, string> dict)
        {
            var query = DBModel.SqlQueryable<dynamic>(sqlStr);

            foreach (var item in dict)
            {
                if (!string.IsNullOrEmpty(item.Value))
                {
                    List<SugarParameter> parameters = new List<SugarParameter>();

                    string conditionStr = string.Empty;

                    if (item.Key.StartsWith("txt_"))
                    {
                        string name = item.Key.Replace("txt_", "");

                        conditionStr = string.Format("{0} like '%'||:{0}||'%'", name);

                        parameters.Add(new SugarParameter(name, item.Value.ToString()));

                    }
                    else if (item.Key.StartsWith("txtEqual_"))
                    {
                        string name = item.Key.Replace("txtEqual_", "");

                        conditionStr = string.Format("{0} = :{0}", name);

                        parameters.Add(new SugarParameter(name, item.Value.ToString()));

                    }
                    else if (item.Key.StartsWith("cb_"))
                    {
                        string name = item.Key.Replace("cb_", "");

                        conditionStr = string.Format("{0} = :{0}", name);

                        parameters.Add(new SugarParameter(name, item.Value.ToString()));
                    }
                    else if (item.Key.StartsWith("dt_"))
                    {
                        string name = item.Key.Replace("dt_", "");

                        DateTime startTime = item.Value.ObjToDate().Date;

                        string startTimeStr = name + "Start";

                        DateTime endTime = startTime.AddDays(1);

                        string endTimeStr = name + "End";

                        conditionStr = string.Format("{0} >=to_date(:{1},'yyyy-mm-dd hh24:mi:ss') and {0} <to_date(:{2},'yyyy-mm-dd hh24:mi:ss')", name, startTimeStr, endTimeStr);

                        parameters.Add(new SugarParameter(startTimeStr, startTime.ToString("yyyy-MM-dd HH:mm:ss")));

                        parameters.Add(new SugarParameter(endTimeStr, endTime.ToString("yyyy-MM-dd HH:mm:ss")));
                    }

                    query = query.Where(conditionStr, parameters);
                }
            }

            return query;
        }

        /// <summary>
        /// 通过 ID 搜索数据库对象
        /// </summary>
        /// <typeparam name="TDBClass">数据表对象</typeparam>
        /// <param name="id">对象ID</param>
        /// <returns>对应ID的对象</returns>
        public virtual TDBClass Get<TDBClass>(string id) where TDBClass : class
        {
            var suagrTableAttribute = typeof(TDBClass).CustomAttributes.Where(c => c.AttributeType == typeof(SugarTable)).FirstOrDefault();

            string tableName = (suagrTableAttribute == null) ? typeof(TDBClass).Name : suagrTableAttribute.ConstructorArguments[0].ObjToString();

            string sql = string.Format("select * from {0} where id=@id", tableName);

            return DBModel.Ado.SqlQuery<TDBClass>(sql,
                new SugarParameter("id", id)).FirstOrDefault();
        }

        public virtual bool Delete<TDBClass>(string id) where TDBClass : class
        {
            var suagrTableAttribute = typeof(TDBClass).CustomAttributes.Where(c => c.AttributeType == typeof(SugarTable)).FirstOrDefault();

            string tableName = (suagrTableAttribute == null) ? typeof(TDBClass).Name : suagrTableAttribute.ConstructorArguments[0].ObjToString();

            string sql = string.Format("delete from {0} where id=@id", tableName);

            return DBModel.Ado.ExecuteCommand(sql,
                new SugarParameter("id", id)) > 0;
        }
    }
}
